package com.YHVision.qiuzhike.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.YHVision.qiuzhike.annotation.AuthCheck;
import com.YHVision.qiuzhike.common.BaseResponse;
import com.YHVision.qiuzhike.common.DeleteRequest;
import com.YHVision.qiuzhike.common.ErrorCode;
import com.YHVision.qiuzhike.common.ResultUtils;
import com.YHVision.qiuzhike.constant.UserConstant;
import com.YHVision.qiuzhike.exception.BusinessException;
import com.YHVision.qiuzhike.exception.ThrowUtils;
import com.YHVision.qiuzhike.model.dto.companyQuestion.CompanyQuestionAddRequest;
import com.YHVision.qiuzhike.model.dto.companyQuestion.CompanyQuestionQueryRequest;
import com.YHVision.qiuzhike.model.dto.companyQuestion.CompanyQuestionUpdateRequest;
import com.YHVision.qiuzhike.model.entity.CompanyQuestion;
import com.YHVision.qiuzhike.model.entity.User;
import com.YHVision.qiuzhike.model.vo.CompanyQuestionVO;
import com.YHVision.qiuzhike.service.CompanyQuestionService;
import com.YHVision.qiuzhike.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 企业问题关联接口
 *
 * @author <a href="">YHVision-小y</a>
 * @from <a href="todo">爱编程学习圈</a>
 */
@RestController
@RequestMapping("/companyQuestion")
@Slf4j
public class CompanyQuestionController {

    @Resource
    private CompanyQuestionService companyQuestionService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建企业问题关联
     *
     * @param companyQuestionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addCompanyQuestion(@RequestBody CompanyQuestionAddRequest companyQuestionAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(companyQuestionAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        CompanyQuestion companyQuestion = new CompanyQuestion();
        BeanUtils.copyProperties(companyQuestionAddRequest, companyQuestion);
        // 数据校验
        companyQuestionService.validCompanyQuestion(companyQuestion, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        companyQuestion.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = companyQuestionService.save(companyQuestion);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newCompanyQuestionId = companyQuestion.getId();
        return ResultUtils.success(newCompanyQuestionId);
    }

    /**
     * 删除企业问题关联
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteCompanyQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        CompanyQuestion oldCompanyQuestion = companyQuestionService.getById(id);
        ThrowUtils.throwIf(oldCompanyQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldCompanyQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = companyQuestionService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新企业问题关联（仅管理员可用）
     *
     * @param companyQuestionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateCompanyQuestion(@RequestBody CompanyQuestionUpdateRequest companyQuestionUpdateRequest) {
        if (companyQuestionUpdateRequest == null || companyQuestionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        CompanyQuestion companyQuestion = new CompanyQuestion();
        BeanUtils.copyProperties(companyQuestionUpdateRequest, companyQuestion);
        // 数据校验
        companyQuestionService.validCompanyQuestion(companyQuestion, false);
        // 判断是否存在
        long id = companyQuestionUpdateRequest.getId();
        CompanyQuestion oldCompanyQuestion = companyQuestionService.getById(id);
        ThrowUtils.throwIf(oldCompanyQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = companyQuestionService.updateById(companyQuestion);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取企业问题关联（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<CompanyQuestionVO> getCompanyQuestionVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        CompanyQuestion companyQuestion = companyQuestionService.getById(id);
        ThrowUtils.throwIf(companyQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(companyQuestionService.getCompanyQuestionVO(companyQuestion, request));
    }

    /**
     * 分页获取企业问题关联列表（仅管理员可用）
     *
     * @param companyQuestionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<CompanyQuestion>> listCompanyQuestionByPage(@RequestBody CompanyQuestionQueryRequest companyQuestionQueryRequest) {
        long current = companyQuestionQueryRequest.getCurrent();
        long size = companyQuestionQueryRequest.getPageSize();
        // 查询数据库
        Page<CompanyQuestion> companyQuestionPage = companyQuestionService.page(new Page<>(current, size),
                companyQuestionService.getQueryWrapper(companyQuestionQueryRequest));
        return ResultUtils.success(companyQuestionPage);
    }

    /**
     * 分页获取企业问题关联列表（封装类）
     *
     * @param companyQuestionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<CompanyQuestionVO>> listCompanyQuestionVOByPage(@RequestBody CompanyQuestionQueryRequest companyQuestionQueryRequest,
                                                               HttpServletRequest request) {
        long current = companyQuestionQueryRequest.getCurrent();
        long size = companyQuestionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<CompanyQuestion> companyQuestionPage = companyQuestionService.page(new Page<>(current, size),
                companyQuestionService.getQueryWrapper(companyQuestionQueryRequest));
        // 获取封装类
        return ResultUtils.success(companyQuestionService.getCompanyQuestionVOPage(companyQuestionPage, request));
    }

    /**
     * 分页获取当前登录用户创建的企业问题关联列表
     *
     * @param companyQuestionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<CompanyQuestionVO>> listMyCompanyQuestionVOByPage(@RequestBody CompanyQuestionQueryRequest companyQuestionQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(companyQuestionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        companyQuestionQueryRequest.setUserId(loginUser.getId());
        long current = companyQuestionQueryRequest.getCurrent();
        long size = companyQuestionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<CompanyQuestion> companyQuestionPage = companyQuestionService.page(new Page<>(current, size),
                companyQuestionService.getQueryWrapper(companyQuestionQueryRequest));
        // 获取封装类
        return ResultUtils.success(companyQuestionService.getCompanyQuestionVOPage(companyQuestionPage, request));
    }

    // endregion
}
